package com.lindroy.androidplayer.logic.network

import com.google.gson.Gson
import com.lindroy.androidplayer.logic.network.HttpNetwork.await
import com.orhanobut.logger.Logger
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * @author Lin
 * @date 2021/4/6
 * @function 网络数据访问入口
 */
object HttpNetwork {
    //region 首页模块
    private val homePageService = ServiceCreator.create<HomePageService>()

    suspend fun getBanners() = homePageService.getBanner().await()

    suspend fun getHomeArticles(page: Int) = homePageService.getArticles(page).await()

    suspend fun getTopArticles() = homePageService.getTopArticles().await()
    //endregion 首页模块

    //region 公众号模块
    private val wxService = ServiceCreator.create<OfficialAccountService>()

    suspend fun getWXChapters() = wxService.getWXChapter().await()

    suspend fun getWXArticles(id: Int, page: Int) = wxService.getWxArticle(id, page).await()
    //endregion 公众号模块

    //region 项目模块
    private val projectService = ServiceCreator.create<ProjectService>()

    suspend fun getProjectTypes() = projectService.getProjectTypes().await()

//    suspend fun getProjectList(id: Int,page: Int) = projectService.getProjectList(page,id).await()
    //endregion 项目模块

    //region 登录模块
    private val loginService =ServiceCreator.create<LoginService>()

    suspend  fun login(name:String,pwd:String) = loginService.login(name,pwd).await()
    //endregion 登录模块

    //region 注册模块
    private val registerService =ServiceCreator.create<RegisterService>()
    suspend fun register(name:String,pwd:String,repwd:String) = registerService.register(name,pwd,repwd).await()
    //endregion end注册模块

    private suspend fun <T> Call<T>.await(): T = suspendCoroutine {
        enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                if (body != null) {
                    it.resume(body)
                } else {
                    it.resumeWithException(RuntimeException("response body is null"))
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {
                it.resumeWithException(t)
            }
        })
    }
}